package top.zhangjianyong.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import top.zhangjianyong.entity.ReptileUrl;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/22 10:36 AM
 */
@Slf4j
public class RequestUtil {


    public static HttpRequest createGet(String url) {
        return HttpUtil
                .createGet(url)
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                .setConnectionTimeout(1000 * 3)
                .setReadTimeout(1000 * 3)
                .setMaxRedirectCount(20);
    }

    public static HttpResult getHtml(ReptileUrl reptileUrl) {
        String url = reptileUrl.getUrl();
        long start = System.currentTimeMillis();
        log.info("请求地址:{}", url);
        HttpRequest get = createGet(url);
        HttpResponse execute = null;
        try {
            execute = get.execute();
        } catch (NullPointerException e) {
            log.info("重定向异常");
            execute = get.setMaxRedirectCount(0).execute();
        }
        int status = execute.getStatus();
        log.info("响应结果：{}", url, status);
        log.info("http请求耗时：{}", System.currentTimeMillis() - start);
        HttpResult result = new HttpResult();

        result.setLocation(execute.header("location"));

        result.setStatus(status);
        setBody(execute, result);

        return result;
    }

    public static void setBody(HttpResponse execute, HttpResult result) {
        String contentType = execute.header("Content-Type");
        String contentLength = execute.header("Content-Length");
        if (!"application/octet-stream".equals(contentType) && !"application/x-msdownload".equals(contentType)) {
            result.setBody(execute.body());
            return;
        }
        long length = 999l;
        long m = 0;
        long k = 0;
        try {
            length = Long.parseLong(contentLength);
            m = length / 1024 / 1024;
            k = length / 1024 % 1024;
        } catch (Exception e) {
            m = -1;
            k = -1;
            log.error(e.getMessage(), e);
        }
        log.info("http请求body长度：{}m{}k", m, k);
        if (m < 5) {
            result.setBody(execute.body());
        } else {
            result.setBody("");
        }

    }

    public static void main(String[] args) {
        String url = "http://mail.126.com/";
        // HttpResult html = getHtml(url);
        //System.out.println(html);
    }
}
